<template>
    <el-dialog
        class="custom-modal"
        :title="title"
        :visible.sync="show"
        :close-on-click-modal="false"
        append-to-body
        top="20vh"
        @open="_open"
        @close="_close"
        @closed="_afterClose"
        v-auto-focus
    >
        <div class="custom-modal-container">
            <div class="select-box">
                <div class="select-tool">
                    <ask-city-cascader
                        ref="cityCascader"
                        v-model="value"
                        @change="handleChange"
                        :showModel="showModel"
                        showNot="city"
                        clear />
                    <el-input class="select-tool-input" v-model="filterName" placeholder="筛选部门"></el-input>
                </div>
                <div class="select-result">
                    <el-checkbox-group v-model="selectedDepartmentList">
                        <el-checkbox
                            @change="changeCheckBox($event, item)"
                            v-for="(item, index) in departmentListRes"
                            :label="item.id"
                            :key="index">
                            <span class="checkbox-span" :title="item.name">{{item.name}}</span>
                        </el-checkbox>
                    </el-checkbox-group>
                </div>
            </div>
            <p>已选择</p>
            <div class="selected-box">
                <el-table
                    :data="tableData"
                    class="pbb__table"
                    header-cell-class-name="pbb__table-thead"
                    cell-class-name="pbb__table-thead-cell"
                    row-class-name="pbb__table-thead-row"
                    style="width: 100%">
                    <el-table-column
                        prop="areaName"
                        label="区域">
                    </el-table-column>
                    <el-table-column
                        prop="departmentName"
                        label="部门">
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        width="80">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" @click="changeCheckBox(false, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    v-show="selectedList.length > 5"
                    class="page"
                    small
                    layout="prev, pager, next"
                    @current-change="changePage"
                    :current-page="currentPage"
                    :page-size="pageSize"
                    :total="selectedList.length">
                </el-pagination>
            </div>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="close">取消</el-button>
            <el-button
                class="sure"
                type="primary"
                @click="saveSelected"
                :loading="ajaxLoader"
            >保存</el-button>
        </div>
    </el-dialog>
</template>

<script lang="ts">
import { Component, Watch, Vue } from "vue-property-decorator";

@Component
export default class SelectDepartment extends Vue {
    title = "所属部门";
    show = false;
    ajaxLoader = false;
    ajaxIndex = 0;

    // 所有被选中的内容
    selectedList: any[] = [];
    // 区域部门被选中的
    selectedDepartmentList: any[] = [];
    // 区域下的部门列表
    departmentList: any[] = [];
    // 筛选后的显示
    departmentListRes: any[] = [];

    // 表格显示内容
    tableData: any = []
    currentPage = 1
    pageSize = 5
    areaValue: any = {};
    showModel: string[] = ['province', 'city', 'area', 'town', 'village']
    value: any = ""
    filterName = ""

    @Watch("filterName")
    changeValue() {
        this.departmentListRes = this.departmentList.filter((item: any) => {
            return item.name.includes(this.filterName);
        });
    }

    async _open() {
        this.$emit("onopen");
        this.selectedDepartmentList = this.selectedList.map((item: any) => item.departmentId || item.id);
        this.changePage("");
        if (this.selectedList.length) {
            this.value = this.selectedList[0].cityCode;
        }
    }

    _close() {
        this.$emit("onclose");
    }

    _afterClose() {
        this.$nextTick(function() {
            this.$emit("onafterclose");
            this.$el.remove && this.$el.remove();
        });
    }

    loader(state: boolean) {
        if (state) {
            if (this.ajaxIndex === 0) this.ajaxLoader = true;
            this.ajaxIndex++;
        } else {
            setTimeout(() => {
                this.ajaxIndex--;
                if (this.ajaxIndex === 0) this.ajaxLoader = false;
            }, 300);
        }
    }

    close() {
        this.show = false;
    }

    // 翻页/获取表格显示内容
    changePage(val: any) {
        this.currentPage = val || this.currentPage;
        const start = (this.currentPage - 1) * this.pageSize;
        this.tableData = this.selectedList.slice(start, start + this.pageSize);
    }

    // 查询政级id
    getAreaId() {
        let name = "";
        for (let i = this.showModel.length - 1; i >= 0; i--) {
            if (this.areaValue[this.showModel[i]].name === "") {
                continue;
            } else {
                name = `askCity${this.showModel[i]}PanelRef`;
                break;
            }
        }
        const list = (this.$refs.cityCascader as any).$refs[name][0].sourceList;
        return list.filter((item: any) => item.code.toString() === this.value)[0].id;
    }

    // 选择地区
    async handleChange(value: any) {
        this.areaValue = value;
        if (!this.value) {
            this.departmentList = [];
            return false;
        }
        const res = await this.$server["org/getDepartmentList"]({
            data: {
                governmentId: this.getAreaId()
            }
        });
        if (res.data.code === 200) {
            this.departmentList = res.data.data;
            this.departmentListRes = this.departmentList.filter((item: any) => {
                return item.name.includes(this.filterName);
            });
        } else {
            this.departmentList = [];
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    // 保存选中的，不是id数组
    saveSelected() {
        this.$emit("sure", {
            selectedList: this.selectedList
        });
    }

    // 选择复选框
    changeCheckBox(val: any, { id, name, departmentId }: { id: string; name: string; departmentId: string }) {
        if (val) {
            this.selectedList.push({
                id: id || departmentId,
                cityCode: this.value,
                departmentName: name,
                areaName: (this.$refs.cityCascader as any).currentLabel
            });
        } else {
            const index = this.selectedList.findIndex((d: any) => (d.id || d.departmentId) === (id || departmentId));
            this.selectedList.splice(index, 1);
            const indexDep = this.selectedDepartmentList.findIndex((d: any) => d === (id || departmentId));
            if (indexDep !== -1) {
                this.selectedDepartmentList.splice(indexDep, 1);
            }
        }
        if (this.selectedList.length / 5 <= this.currentPage - 1 && this.selectedList.length > 4) {
            this.changePage(this.currentPage - 1);
        } else {
            this.changePage("");
        }
    }
}
</script>
<style scoped lang="scss">
.custom-modal {
    margin: 0;
    & /deep/ {
        .el-dialog {
            width: 600px;
            margin-top: 12vh!important;
        }
    }
}
.custom-modal-container {
    .select-box {
        border: 1px solid #e3e3e3;
        border-radius: 5px;
        padding: 5px;
        .select-tool {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            .select-tool-input {
                width: 200px;
                margin-left: 20px;
            }
        }
        .select-result {
            margin-top: 5px;
            height: 150px;
            overflow: auto;
            border: 1px solid #eeeeee;
            border-radius: 5px;
            padding: 5px;
            .el-checkbox {
                display: inline-flex;
                justify-content: flex-start;
                align-items: center;
                .checkbox-span {
                    display: inline-block;
                    width: 120px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
            }
        }
    }
    .selected-box {
        .page {
            text-align: center;
        }
    }
}
</style>
